package com.admin.controller;


import cn.hutool.core.io.FileUtil;
import com.admin.entity.Admin;
import com.admin.entity.AdminRole;
import com.admin.service.IAdminRoleService;
import com.admin.service.IAdminService;
import com.admin.service.IAdminshuchaxunService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.token.JwtUtil;
import com.util.PasswordUtil;
import com.util.PhoneNumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 管理员模块控制层
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IAdminRoleService adminRoleService;

    @Autowired
    private HttpServletRequest request;
    @Value("${upload.tmp.dir}")
    private String tmp;
    @Value("${upload.dir}")
    private String upload;


    /**
     * 判断账号密码是否正确,登录失败次数大于十次的ip一分钟内不得再次登录
     */
    @RequestMapping("/login")
    public ResponseBean login(HttpServletRequest request, HttpServletResponse response, String username, String password) throws Exception {
        return adminService.tologin(request, response, username, password);
    }

    /**
     * 新增子用户
     *
     * @param admin
     * @returnu
     */
    @RequestMapping("/addser")
    public ResponseBean adduser(Admin admin) {
        Integer addusernumber = null;
        boolean bphone = false;
        if (admin.getAdminPersonInCharge() == null && admin.getAdminParent() == null) {
            return new ResponseBean(500, "添加失败", null);
        }
        if (admin.getAdminPhone() != null && admin.getAdminPhone() != "") {
            bphone = PhoneNumUtil.ifPhone(admin.getAdminPhone());
        }
        if (bphone == false) {
            return new ResponseBean(500, "电话号码不存在", null);
        }
        boolean tupian = admin.getAdminHeadPortrait().isEmpty() ? false : true;
        //检查昵称是否已存在
        boolean selAdminname = adminService.seladminName(admin.getAdminName());
        if (selAdminname == true) {
            return new ResponseBean(500, "昵称已存在", null);
        }
        if (tupian == true && bphone == true) {
            addusernumber = adminService.adduser(admin);
        }
        if (addusernumber > 0 && bphone && tupian) {
            //图片上传
            String path = request.getServletContext().getRealPath("images");
            File file = new File(path);
            if (file.exists() == false) {
                file.mkdirs();
            }
            FileUtil.copy(tmp + "/" + admin.getAdminHeadPortrait(), path + "/" + admin.getAdminHeadPortrait(), true);
            return new ResponseBean(200, "添加成功", null);
        } else {
            return new ResponseBean(500, "该电话号码已存在", null);
        }
    }

    /**
     * 用户管理查询
     *
     * @param page
     * @param limit
     * @param m
     * @return
     */
    @RequestMapping("/searchyhgl")
    public ResponseBean searchyhgl(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map m) {
            IPage result = adminService.searchyhgl(page, limit, m);
            return new ResponseBean(0, result.getTotal(), result.getRecords());
    }

    /**
     * 详情编辑修改(根据id修改) , 同时修改admin_role表 ， 昵称不能重复 ， 电话号码格式需正确
     * @param admin
     * @return
     */
    @RequestMapping("/updataAdmin")
    public ResponseBean updataAdmin(Admin admin) {
        //1.先处理昵称重复问题
        String admin_name = admin.getAdminName();
        int admin_id = admin.getAdminId();
        if (admin_name == null && admin_name == "") {
            return new ResponseBean(500, "昵称不能为空", null);
        }
        //2.处理电话号码格式问题
        boolean ifPhonenumber = PhoneNumUtil.ifPhone(admin.getAdminPhone());
        if (ifPhonenumber == false) {

            return new ResponseBean(500, "电话号码格式不正确", null);
        }
        int bianjiadmin;
        //4.修改其他内容
        try {
            bianjiadmin = adminService.updatebyadmin(admin);
        } catch (Exception e) {
            return new ResponseBean(500, "昵称已存在或电话号码已存在", null);
        }

        if ( bianjiadmin > 0) {
            String path = request.getServletContext().getRealPath("images");
            File file = new File(path);
            if (file.exists() == false) {
                file.mkdirs();
            }
            FileUtil.copy(tmp + "/" + admin.getAdminHeadPortrait(), path + "/" + admin.getAdminHeadPortrait(), true);

            return new ResponseBean(200, "修改成功", null);
        } else {
            return new ResponseBean(500, "修改失败", null);
        }
    }

    /**
     * 获取当前用户沃币
     *
     * @return
     * @throws Exception
     */

    @RequestMapping("/getMoney")
    public ResponseBean getMoney(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
       // System.out.println(token);
        if (token==null)
        {
            System.out.println("token is null");
        }
        String username = JwtUtil.getUsername(token);

        if (token == null || username == null) {
            return new ResponseBean(401, "没有登录", null);
        }
        int money = adminService.getMoney(username);
        return new ResponseBean(200, "返回成功", money);
    }

    @Autowired
    private IAdminshuchaxunService adminshuchaxunService;

    /**
     * 树的接口
     * 根据当前用户id查询用户信息包含所有下级以及下级的下级
     *
     * @return
     */
    @RequestMapping("/selectShujsonById")
    public ResponseBean SelectshujsonByid(String token,Integer adminidnow) {
        String id = JwtUtil.getUsername(token);
        if (id==null)
        {
            return new ResponseBean(401, "登录失败", null);
        }
        String jsonArray = adminshuchaxunService.getTreeByUserId(id);
        return new ResponseBean(200, "请求成功", jsonArray);
    }

    @RequestMapping("/updateselct")
    public ResponseBean updateselct(@RequestParam Map adminname) {

        List updateselct = adminService.updateselct(adminname);
        if (updateselct != null && updateselct.size() > 0) {
            return new ResponseBean(200, "下拉列表的数据", updateselct);
        } else {
            return new ResponseBean(500, "请求失败", null);
        }
    }

    /**
     * 查询昵称，头像
     *
     * @return
     */
    @RequestMapping("/chaUser")
    public ResponseBean chauserMassge(Integer admin_id) {
        Admin admin = adminService.chaUser(admin_id);
        if (admin != null) {
            return new ResponseBean(200, "查询成功", admin);
        }
        return new ResponseBean(500, "查询失败", null);
    }


    @RequestMapping("/xiuPassword")
    public ResponseBean xiugaipassword(String yuanpassword, String password, String adminName) {

        List<Admin> yuanpasswordlist = adminService.selctyuanpassword(adminName);
        if (!PasswordUtil.jiami(yuanpassword).equals(yuanpasswordlist.get(0).getAdminPassword()))
        {
            return new ResponseBean(500, "您写的原密码不正确", null);
        }
        int adminPassnum = adminService.xiuPassword(password ,adminName);
        if(adminPassnum<=0) {
        return new ResponseBean(500, "修改失败", null);
        }
        return new ResponseBean(200, "修改成功", null);
    }


}
